package com.xgl.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.xgl.pojo.*;
import com.xgl.service.IDepartmentService;
import com.xgl.service.IMajorService;
import com.xgl.service.INationService;
import com.xgl.service.IStudentinfoService;
import com.xgl.utils.Md5Utils;
import com.xgl.utils.sha256Utils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.nio.cs.ext.MacDingbat;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生个人信息 前端控制器
 * </p>
 *
 * @author 最最帅气的熊国林
 * @since 2021-05-09
 */
@RestController
@RequestMapping("/student/info")
public class StudentinfoController {
    @Autowired
    private IStudentinfoService iStudentinfoService;
    @Autowired
    private IDepartmentService iDepartmentService;
    @Autowired
    private IMajorService iMajorService;
    @Autowired
    private INationService iNationService;


    @ApiOperation(value = "生成学生hash")
    @GetMapping("compute/{id}")
    public String computeHash(@PathVariable Integer id) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        List<Studentinfo> list = iStudentinfoService.getStudentInfo(id);
        Map<String,String> map = new HashMap<String,String>();
        list.forEach(studentinfo -> {
            map.put("s_type",studentinfo.getS_type().toString());
            map.put("learn_form",studentinfo.getLearn_form().toString());
            map.put("id",studentinfo.getId().toString());
            map.put("s_number",studentinfo.getS_number().toString());
            map.put("name",studentinfo.getName().toString());
            map.put("e_name",studentinfo.getE_name().toString());
            map.put("nationId",studentinfo.getNationId().toString());
            //map.put("nation",studentinfo.getNation().toString());
            map.put("sex",studentinfo.getSex().toString());
            map.put("grade",studentinfo.getGrade().toString());
            map.put("s_year",studentinfo.getS_year().toString().toString());
            map.put("s_level",studentinfo.getS_level().toString());
            map.put("s_category",studentinfo.getS_category().toString());
            map.put("departmentId",studentinfo.getDepartmentId().toString());
           // map.put("department",studentinfo.getDepartment().toString());
            map.put("majorId",studentinfo.getMajorId().toString());
            //map.put("major",studentinfo.getMajor().toString());
            map.put("create_time",studentinfo.getCreate_time().toString());
            map.put("graduation_time",studentinfo.getGraduation_time().toString());
            map.put("admin_department",studentinfo.getAdmin_department().toString());
            map.put("statue",studentinfo.getStatue().toString());
            map.put("is_living",studentinfo.getIs_living().toString());
            map.put("is_leaving",studentinfo.getIs_leaving().toString());
            map.put("admin_class",studentinfo.getAdmin_class().toString());
            map.put("school_area",studentinfo.getSchool_area().toString());
            map.put("is_delete",studentinfo.getIs_delete().toString());
//            map.put("hash_code",studentinfo.getHash_code().toString());
//            map.put("previousHash",studentinfo.getPreviousHash().toString());
        });
        String hashCode = Md5Utils.SHA256(
                map.get("s_type") + map.get("learn_form") +
                        map.get("id") +map.get("s_number") +
                        map.get("name") +map.get("e_name") +
                        map.get("nationId") +map.get("sex") +
                        map.get("grade") +map.get("s_year") +
                        map.get("s_level") +map.get("s_category") +
                        map.get("departmentId") +map.get("majorId") +
                        map.get("create_time") +map.get("graduation_time") +
                        map.get("admin_department") +map.get("statue") +
                        map.get("is_living") +map.get("is_leaving") +
                        map.get("admin_class") +map.get("school_area") +
                        map.get("is_delete")
        );
        iStudentinfoService.insertHashCode(id,hashCode);

        System.out.println("hashCode is " + hashCode);
        return hashCode;
    }

    @ApiOperation(value = "获取所有学生信息（分页）")
    @GetMapping("/")
    public RespPageBean getStudentInfoByPage(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer size,
                                             Studentinfo studentinfo, LocalDate[] beginDateScope) {
        return iStudentinfoService.getStudentInfoByPage(currentPage, size, studentinfo, beginDateScope);
    }

    @ApiOperation(value = "增加学生信息")
    @PostMapping("/")
    public RespBean addStudentInfo(@RequestBody Studentinfo studentinfo) {
        return iStudentinfoService.addStudentInfo(studentinfo);
    }

    @ApiOperation(value = "更新学生信息")
    @PutMapping("/")
    public RespBean updateStudentInfo(@RequestBody Studentinfo studentinfo) {
        if (iStudentinfoService.updateById(studentinfo)) {
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation(value = "删除学生信息")
    @DeleteMapping("/{id}")
    public RespBean deleteStudentInfo(@PathVariable Integer id) {
        if (iStudentinfoService.removeById(id)) {
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "导出学生数据")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportStudentInfo(HttpServletResponse response) {
        List<Studentinfo> list = iStudentinfoService.getStudentInfo(null);
        ExportParams params = new ExportParams("学生信息表", "学生信息表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Studentinfo.class, list);
        //输出
        ServletOutputStream outputStream = null;
        try {
            //流形式
            response.setHeader("content-type", "application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("学生信息表.xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入学生数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "上传文件", dataType = "MultipartFile")})
    @PostMapping("/import")
    public RespBean importStudentInfo(MultipartFile file) {
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Nation> nations = iNationService.list();
        List<Major> majors = iMajorService.list();
        List<Department> departments = iDepartmentService.list();
        try {
            List<Studentinfo> list = ExcelImportUtil.importExcel(file.getInputStream(), Studentinfo.class, params);
            list.forEach(studentinfo -> {
                //民族id
                studentinfo.setNationId(nations.get(nations.indexOf(new Nation(studentinfo.getNation().getName()))).getId());
                //专业id
                studentinfo.setMajorId(majors.get(majors.indexOf(new Major(studentinfo.getMajor().getName()))).getId());
                //学院id
                studentinfo.setDepartmentId(departments.get(departments.indexOf(new Department(studentinfo.getDepartment().getName()))).getId());
                //职称id

            });
            if (iStudentinfoService.saveBatch(list)) {
                return RespBean.success("导入成功");
            }
            return RespBean.error("导入失败");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }

    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nation")
    public List<Nation> getAllNation() {
        return iNationService.list();
    }

    @ApiOperation(value = "获取所有专业")
    @GetMapping("/major")
    public List<Major> getAllPosition() {
        return iMajorService.list();
    }

    @ApiOperation(value = "获取所有学院")
    @GetMapping("/department")
    public List<Department> getAllDepartment() {
        return iDepartmentService.list();
    }


}
